import { ref, computed } from 'vue'
import { esSearch, getSearchHistory, deleteSearchHistory } from '@/api/search'
import { ElMessage } from 'element-plus'

/**
 * Elasticsearch 搜索组合式函数
 * @param {string} indexName - ES索引名称
 * @param {number} defaultPageSize - 默认每页条数
 * @returns {Object} 搜索相关的状态和方法
 */
export function useElasticSearch(indexName, defaultPageSize = 10) {
  // 搜索状态
  const searchKeyword = ref('')
  const searchResults = ref([])
  const searchHistory = ref([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(defaultPageSize)
  const total = ref(0)
  const totalPages = ref(0)

  // 是否有搜索结果
  const hasResults = computed(() => searchResults.value.length > 0)

  // 是否正在搜索
  const isSearching = computed(() => !!searchKeyword.value.trim())

  /**
   * 执行搜索
   * @param {string} keyword - 搜索关键词（可选，默认使用searchKeyword）
   * @param {number} page - 页码（可选，默认使用currentPage）
   */
  const search = async (keyword = null, page = null) => {
    const finalKeyword = keyword !== null ? keyword : searchKeyword.value
    const finalPage = page !== null ? page : currentPage.value

    if (!finalKeyword.trim()) {
      ElMessage.warning('请输入搜索关键词')
      return
    }

    loading.value = true
    try {
      const response = await esSearch({
        index: indexName,
        keyword: finalKeyword.trim(),
        page: finalPage,
        size: pageSize.value
      })

      if (response.code === 200 && response.data) {
        searchResults.value = response.data.docs || []
        total.value = response.data.total || 0
        totalPages.value = response.data.total_pages || 0
        currentPage.value = finalPage

        if (searchResults.value.length === 0) {
          ElMessage.info('未找到相关结果，请尝试其他关键词')
        } else {
          ElMessage.success(`找到 ${total.value} 条相关结果`)
        }
      } else {
        ElMessage.error(response.message || '搜索失败')
        searchResults.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('ES搜索失败:', error)
      
      // 根据不同的错误类型显示不同的提示
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('搜索超时，请检查Elasticsearch服务是否启动')
      } else if (error.code === 'ERR_NETWORK') {
        ElMessage.error('网络连接失败，请检查后端服务是否启动')
      } else if (error.response) {
        const msg = error.response.data?.message || '搜索失败'
        ElMessage.error(msg)
      } else {
        ElMessage.error('搜索服务暂时不可用，请稍后重试')
      }
      
      searchResults.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  /**
   * 分页搜索
   * @param {number} page - 目标页码
   */
  const searchPage = async (page) => {
    if (page < 1 || page > totalPages.value) return
    currentPage.value = page
    await search(searchKeyword.value, page)
  }

  /**
   * 上一页
   */
  const prevPage = async () => {
    if (currentPage.value > 1) {
      await searchPage(currentPage.value - 1)
    }
  }

  /**
   * 下一页
   */
  const nextPage = async () => {
    if (currentPage.value < totalPages.value) {
      await searchPage(currentPage.value + 1)
    }
  }

  /**
   * 加载搜索历史
   */
  const loadSearchHistory = async () => {
    try {
      const response = await getSearchHistory(indexName)
      if (response.code === 200 && Array.isArray(response.data)) {
        // Redis返回的是bytes，需要转换
        searchHistory.value = response.data
          .map(item => {
            if (typeof item === 'string') {
              return item
            }
            // 处理bytes类型（b'keyword'格式）
            const str = String(item)
            const match = str.match(/b'(.+?)'/)
            return match ? match[1] : str
          })
          .slice(0, 10) // 只显示最近10条
      }
    } catch (error) {
      console.error('加载搜索历史失败:', error)
    }
  }

  /**
   * 清空搜索历史
   */
  const clearSearchHistory = async () => {
    try {
      const response = await deleteSearchHistory(indexName)
      if (response.code === 200) {
        searchHistory.value = []
        ElMessage.success('搜索历史已清空')
      } else {
        ElMessage.error('清空失败')
      }
    } catch (error) {
      console.error('清空搜索历史失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }

  /**
   * 重置搜索
   */
  const resetSearch = () => {
    searchKeyword.value = ''
    searchResults.value = []
    currentPage.value = 1
    total.value = 0
    totalPages.value = 0
  }

  /**
   * 从历史记录搜索
   * @param {string} keyword - 历史关键词
   */
  const searchFromHistory = async (keyword) => {
    searchKeyword.value = keyword
    currentPage.value = 1
    await search(keyword, 1)
  }

  return {
    // 状态
    searchKeyword,
    searchResults,
    searchHistory,
    loading,
    currentPage,
    pageSize,
    total,
    totalPages,
    hasResults,
    isSearching,
    
    // 方法
    search,
    searchPage,
    prevPage,
    nextPage,
    loadSearchHistory,
    clearSearchHistory,
    resetSearch,
    searchFromHistory
  }
}

